package com.mls.wms.android.widget.other;

import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.http.RequestManager;
import com.github.jjobes.slidedatetimepicker.SlideDateTimeListener;
import com.github.jjobes.slidedatetimepicker.SlideDateTimePicker;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.YAxisValueFormatter;
import com.mls.wms.android.R;
import com.mls.wms.android.adapter.SimpleDropDownAdapter;
import com.mls.wms.android.constant.DrawColorUtil;
import com.mls.wms.android.constant.ServicePort;
import com.mls.wms.android.extend.AnimDialogFragment;
import com.mls.wms.android.extend.BaseFragmentActivity;
import com.mls.wms.android.extend.ChartLineMarkerView;
import com.mls.wms.android.model.ApiResult;
import com.mls.wms.android.model.DeliveryProgressModel;
import com.mls.wms.android.model.DropDownItemModel;
import com.mls.wms.android.model.WarehouseModel;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by 2014-400 on 2015-10-30.
 */
public class DeliveryProgressActivity extends BaseFragmentActivity {
    private static final String[] CHART_LABEL =
            {
                    "创建", "取消", "分配", "拣货", "复核", "交接"
            };
    private BarChart mChart;
    private EditText etBegin;
    private EditText etEnd;
    private Button btnQuery;

    private String warehouseNo = "";
    private Spinner spWarehouse;
    private SimpleDropDownAdapter adapter;
    private List<DropDownItemModel> listSpinner;

    private TextView tvWarehouse;
    private TextView tvBegin;
    private TextView tvEnd;
    private TextView tvMore;

    private LinearLayout layoutBegin;
    private LinearLayout layoutEnd;

    private AnimDialogFragment progressDialog = null;
    private boolean isFirst = true;

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("warehouseNo", warehouseNo);
        super.onSaveInstanceState(outState);
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_summary_delivery_progress);

        //弹出框
        progressDialog = new AnimDialogFragment();
        progressDialog.setResId(R.drawable.anim_progress_dialog);

        mChart = (BarChart) findViewById(R.id.chart1);
        btnQuery = (Button) findViewById(R.id.act_summary_delivery_progress_btn_query);
        etBegin = (EditText) findViewById(R.id.act_summary_delivery_progress_et_begin);
        etEnd = (EditText) findViewById(R.id.act_summary_delivery_progress_et_end);
        spWarehouse = (Spinner) findViewById(R.id.act_summary_delivery_progress_sp_warehouse);

        tvMore = (TextView) findViewById(R.id.act_summary_delivery_progress_tv_more);
        tvWarehouse = (TextView) findViewById(R.id.act_summary_delivery_progress_tv_warehouse);
        tvBegin = (TextView) findViewById(R.id.act_summary_delivery_progress_tv_begin);
        tvEnd = (TextView) findViewById(R.id.act_summary_delivery_progress_tv_end);
        this.tvMore.setTypeface(_BaseApplication.getIconFont());
        tvWarehouse.setTypeface(_BaseApplication.getIconFont());
        tvBegin.setTypeface(_BaseApplication.getIconFont());
        tvEnd.setTypeface(_BaseApplication.getIconFont());

        layoutBegin = (LinearLayout) findViewById(R.id.act_summary_delivery_progress_layout_begin);
        layoutEnd = (LinearLayout) findViewById(R.id.act_summary_delivery_progress_layout_end);

        setChart(mChart);

        //关闭软键盘
        etBegin.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                etBegin.setInputType(InputType.TYPE_NULL);
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    showDateTimeDialog(etBegin);
                    return true;
                }
                return false;
            }
        });
        etEnd.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                etEnd.setInputType(InputType.TYPE_NULL);
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    showDateTimeDialog(etEnd);
                    return true;
                }
                return false;
            }
        });
        etBegin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDateTimeDialog(etBegin);
            }
        });
        etEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDateTimeDialog(etEnd);
            }
        });

        spWarehouse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                warehouseNo = listSpinner.get(position).getValue();
                //首次进入页面加载图表
                if (isFirst == true && position == 0) {
                    loadDeliveryProgress(mChart);
                    isFirst = false;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                warehouseNo = "";
            }
        });
        //更多
        tvMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layoutBegin.setVisibility(View.VISIBLE);
                layoutEnd.setVisibility(View.VISIBLE);
                tvMore.setVisibility(View.GONE);
            }
        });
        //查询
        btnQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layoutBegin.setVisibility(View.GONE);
                layoutEnd.setVisibility(View.GONE);
                tvMore.setVisibility(View.VISIBLE);

                loadDeliveryProgress(mChart);
            }
        });

        loadWarehouse(this.spWarehouse);
    }

    private void showDateTimeDialog(final EditText editText) {
        final SimpleDateFormat mFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        Date initDate = null;
        if (TextUtils.isEmpty(editText.getText().toString())) {
            initDate = new Date();
        } else {
            try {
                initDate = mFormatter.parse(editText.getText().toString());
            } catch (ParseException e) {
                initDate = new Date();
                e.printStackTrace();
            }
        }

        new SlideDateTimePicker.Builder(getSupportFragmentManager())
                .setListener(new SlideDateTimeListener() {
                    @Override
                    public void onDateTimeSet(Date date) {
                        editText.setText(mFormatter.format(date));
                    }
                })
                .setTheme(SlideDateTimePicker.HOLO_LIGHT)
                .setInitialDate(initDate)
                .setIs24HourTime(true)
                .build()
                .show();
    }

    private void setChart(BarChart mChart) {
        mChart.setDescription("");//描述
        mChart.setNoDataTextDescription("无数据"); // 如果没有数据的时候，会显示这个，类似ListView的EmptyView
        mChart.setDrawGridBackground(false); // 是否显示表格颜色
        mChart.setGridBackgroundColor(Color.WHITE & 0x70FFFFFF); // 表格的的颜色，在这里是是给颜色设置一个透明度

        mChart.setPinchZoom(false);
        mChart.setDrawBarShadow(false);
        mChart.setDrawGridBackground(false);
        mChart.setTouchEnabled(true); // 设置是否可以触摸
        mChart.setDragEnabled(false);// 是否可以拖拽
        mChart.setScaleEnabled(false);// 是否可以缩放

        //mChart.setDrawBarShadow(true);//阴影

        //mChart.animateX(2500);

        ChartLineMarkerView mv = new ChartLineMarkerView(this, R.layout.chart_line_marker_view);
        mChart.setMarkerView(mv);

        //图例
        Legend legend = mChart.getLegend();
        legend.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
        //legend.setTypeface(_BaseApplication.getOpenSansRegular());
        legend.setYOffset(5f);
        legend.setYEntrySpace(0f);
        legend.setTextSize(10f);

        //X坐标样式
        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTypeface(_BaseApplication.getOpenSansRegular());
        xAxis.setDrawGridLines(true);
        //xAxis.setGridLineWidth(1f);
        xAxis.setDrawAxisLine(true);
        xAxis.setAxisLineWidth(1f);
        xAxis.setAxisLineColor(getResources().getColor(R.color.gray));
        xAxis.setGridColor(getResources().getColor(R.color.gray));

        //Y轴样式。
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setValueFormatter(new YAxisValueFormatter() {
            @Override
            public String getFormattedValue(float v, YAxis yAxis) {
                return String.valueOf(Double.valueOf(v).intValue());
            }
        });
        leftAxis.setTypeface(_BaseApplication.getOpenSansRegular());
        leftAxis.setDrawGridLines(true);
        //leftAxis.setGridLineWidth(1f);
        leftAxis.setDrawAxisLine(true);
        leftAxis.setAxisLineWidth(1f);
        leftAxis.setAxisLineColor(getResources().getColor(R.color.gray));
        leftAxis.setGridColor(getResources().getColor(R.color.gray));
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(30f);

        //Y坐标
        YAxis rightAxis = mChart.getAxisRight();
        //rightAxis.setEnabled(false);
        rightAxis.setValueFormatter(new YAxisValueFormatter() {
            @Override
            public String getFormattedValue(float v, YAxis yAxis) {
                return String.valueOf(Double.valueOf(v).intValue());
            }
        });
        rightAxis.setTypeface(_BaseApplication.getOpenSansRegular());
        rightAxis.setDrawGridLines(true);
        //leftAxis.setGridLineWidth(1f);
        rightAxis.setDrawAxisLine(true);
        rightAxis.setAxisLineWidth(1f);
        rightAxis.setAxisLineColor(getResources().getColor(R.color.gray));
        rightAxis.setGridColor(getResources().getColor(R.color.gray));
        rightAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        rightAxis.setSpaceTop(30f);
    }

    private void draw(BarChart mChart, DeliveryProgressModel model) {
        //X坐标数据
        ArrayList<String> xVals = new ArrayList<String>();
        for (int i = 0; i < CHART_LABEL.length; i++) {
            xVals.add(CHART_LABEL[i]);
        }

        //Y坐标数据
        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
        for (int i = 0; i < model.getData().length; i++) {
            yVals1.add(new BarEntry(model.getData()[i], i));
        }

        BarDataSet set1 = new BarDataSet(yVals1, model.getSeries());
        //set1.setColor(getResources().getColor(R.color.menu_11));
        set1.setColors(DrawColorUtil.VORDIPLOM_COLORS);
        set1.setDrawValues(false);//顶部显示值

        ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>();
        dataSets.add(set1);

        BarData data = new BarData(xVals, dataSets);


        data.setGroupSpace(10f);

        mChart.setData(data);
        mChart.invalidate();
    }

    private void loadWarehouse(Spinner spinner) {
        get(ServicePort.getUrl(ServicePort.GetWarehouse), null, new RequestManager.RequestListener() {
            @Override
            public void onRequest() {

            }

            @Override
            public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                String errorMsg = null;
                try {
                    ApiResult result = new ApiResult();
                    result = result.parseJson(s);
                    if (result != null && result.getSuccess() == true) {
                        if (result.getResult() == null || TextUtils.isEmpty(result.getResult())) {
                            throw new Exception(getResources().getString(R.string.exception_no_data));
                        }

                        WarehouseModel model = new WarehouseModel();
                        List<WarehouseModel> listWarehouse = model.parseJsons(result.getResult());

                        listSpinner = new ArrayList<DropDownItemModel>();
                        for (WarehouseModel item : listWarehouse) {
                            listSpinner.add(new DropDownItemModel(item.getWarehouseName(), item.getWarehouseNo()));
                        }

                        adapter = new SimpleDropDownAdapter(DeliveryProgressActivity.this, listSpinner);
                        spWarehouse.setAdapter(adapter);

                        return;
                    } else {
                        errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                    }
                } catch (Exception e) {
                    errorMsg = e.getMessage();
                    e.printStackTrace();
                }

                if (false == TextUtils.isEmpty(errorMsg)) {
                    Toast.makeText(DeliveryProgressActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(String s, String s2, int i) {
                Toast.makeText(DeliveryProgressActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        }, 1);
    }

    private void loadDeliveryProgress(final BarChart mChart) {
        progressDialog.show(getFragmentManager(), this.toString());

        //2015-10-20 15:23 空格处理
        String startTime = etBegin.getText().toString().replace(" ", "%20");
        String endTime = etEnd.getText().toString().replace(" ", "%20");
        String url = ServicePort.getUrl(ServicePort.GetDeliveryProgress).replace("{restfulid0}", warehouseNo) + "?startTime=" + startTime + "&endTime=" + endTime;
        get(url, null, new RequestManager.RequestListener() {
            @Override
            public void onRequest() {

            }

            @Override
            public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                String errorMsg = null;
                try {
                    ApiResult result = new ApiResult();
                    result = result.parseJson(s);
                    if (result != null && result.getSuccess() == true) {
                        if (result.getResult() == null || TextUtils.isEmpty(result.getResult())) {
                            throw new Exception(getResources().getString(R.string.exception_no_data));
                        }

                        DeliveryProgressModel model = new DeliveryProgressModel();
                        model = model.parseJson(result.getResult());

                        draw(mChart, model);

                        progressDialog.dismiss();
                        return;
                    } else {
                        errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                    }
                } catch (Exception e) {
                    errorMsg = e.getMessage();
                    e.printStackTrace();
                }

                progressDialog.dismiss();
                if (false == TextUtils.isEmpty(errorMsg)) {
                    Toast.makeText(DeliveryProgressActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(String s, String s2, int i) {
                progressDialog.dismiss();
                Toast.makeText(DeliveryProgressActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        }, 1);
    }


    @Override
    public boolean getScannerVisible() {
        return false;
    }

    @Override
    public int getTopNameResId() {
        return R.string.title_delivery_progress;
    }
}
